#include <iomanip>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::fixed;
using std::setprecision;

#include <fstream>
using std::ofstream;
using std::ifstream;
using std::streambuf;

#include <vector>
using std::vector;

#include "Account.h"
#include "SavingsAccount.h"
#include "CheckingAccount.h"

int main(int argc, const char *argv[])
{
    ofstream out_file ("cout.txt");
    streambuf* buffer = cout.rdbuf ();
    cout.rdbuf (out_file.rdbuf ());

    vector < Account* > accounts;

    accounts.push_back (new SavingsAccount (25.0, .03));
    accounts.push_back (new CheckingAccount (80.0, 1.0));
    accounts.push_back (new SavingsAccount (200.0, .015));
    accounts.push_back (new CheckingAccount (400.0, .5));

    cout << fixed << setprecision (2);

    size_t i;
    for (i = 0; i < accounts.size (); i++) {
        cout << "\nAccount " << i + 1 << " balance $"
             << accounts[i]->getBalance ();

        double withdrawalAmount = 0.0;
        cout << "\nEnter an amount to withdraw from Account" << i + 1
             << ": ";
        cin >> withdrawalAmount;
        accounts[i]->debit (withdrawalAmount);

        double depositAmount = 0.0;
        cout << "Enter an amount to deposit inti Account" << i + 1
             << " :";
        cin >> depositAmount;
        accounts[i]->credit (depositAmount);

        SavingsAccount *savingsAccountPtr = 
            dynamic_cast < SavingsAccount* > (accounts[i]);
        if (savingsAccountPtr)
        {
            double interestEarned = savingsAccountPtr->calculateInterest ();
            cout << "Adding $" << interestEarned << " interest to Account"
                 << i + 1 << "(a SavingsAccount)" << endl;
            savingsAccountPtr->credit (interestEarned);
        }

        cout << "Updated Account" << i + 1 << " balance: $"
             << accounts[i]->getBalance () << endl;

    }

    cout.rdbuf (buffer);
    out_file.close ();

    cout << "Output has been saved in cout.txt\n"
         << "Now read the cout.txt:" << endl;
    ifstream in_file ("cout.txt");
    cout << in_file.rdbuf ();

    return 0;
}
